package com.example.simple.framework.security.service;

import cn.hutool.core.util.StrUtil;
import com.example.simple.project.sys.entity.SysResource;
import com.example.simple.project.sys.entity.SysRole;
import com.example.simple.project.sys.entity.SysUser;
import com.example.simple.project.sys.service.ISysResourceService;
import com.example.simple.project.sys.service.ISysRoleService;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version 1.0.0
 * @className: SysPermissionService
 * @description:
 * @author: LiJunYi
 * @create: 2022/7/26 12:36
 */
@Component
public class SysPermissionService
{
    private final ISysRoleService roleService;
    private final ISysResourceService resourceService;

    /**
     * 构造器注入
     *
     * @param roleService     角色服务
     * @param resourceService 资源服务
     */
    public SysPermissionService(ISysRoleService roleService, ISysResourceService resourceService) {
        this.roleService = roleService;
        this.resourceService = resourceService;
    }

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user)
    {
       return roleService.getRolePermissionByUserId(user.getId());
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user)
    {
        List<SysResource> resources = resourceService.listResourceByUserId(user.getId());
        List<String> perms = resources.stream().map(SysResource::getPermission).collect(Collectors.toList());
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StrUtil.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 获取角色通过用户id
     *
     * @param user 用户
     * @return {@link List}<{@link SysRole}>
     */
    public List<SysRole> getRolesByUserId(SysUser user)
    {
        return roleService.getRolesByUserId(user.getId());
    }
}
